<?php
// +----------------------------------------------------------------------
// | TVSD  [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2023 http://xgx.517528.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 王斌
// +----------------------------------------------------------------------

namespace app\admin\controller\tvsd;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use \app\admin\model\tvsd\Cd;
use \app\admin\model\tvsd\Cl;

/**
 * 调度派车管理
 *
 * @icon fa fa-circle-o
 */
class Pc extends Backend
{

    /**
     * DdPc模型对象
     * @var \app\admin\model\tvsd\DdPc
     */
    protected $model = null;
    protected $dataLimit = 'auth'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'admin_id'; //数据关联字段,当前控制器对应的模型表中必须存在该字段
    protected $noNeedLogin = ['dysj'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\tvsd\DdPc;
        $this->assign("statusList", $this->model->getStatusList());
        $this->assign("fsList", $this->model->getFsList());
        $this->assign("status1List", $this->model->getStatus1List());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->searchFields = 'ddh,kh,cd,cp,jsy1,jsy2,scd,mdd,ddr';
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 超级编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function cjxg($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // dump( $row);
            $this->view->assign('row', $row);
            return $this->view->fetch('edit');
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 旅游车派车记录按月
     */
    public function pcjl()
    {

        $this->relationSearch = true;
        if ($this->request->isAjax()) {
            $a = $this->request->param('filter'); //接收普通搜索数据
            $date = json_decode($a, true); //josn数据到数组
            // echo date('d',time());
            // exit;
            //先查询出所有旅游车队名称
            // $list = Category::field('id,name')->wherelike('name', '%旅游车队')->select();
            $admin_id = $this->getDataLimitAdminIds(); //查询用户组id
            if(key_exists('cd',$date)){
                $list = Cd::where('name',$date['cd'])->select(); //按用户id查询权限数据
            }else{
                $list = Cd::where('admin_id', 'in', $admin_id)->select(); //按用户id查询权限数据
            }
            
            // dump(count($list,0));
            $list = collection($list)->toArray();
            $gd = array();
            //循环查询车辆数据
            $t = 0;
            
            for ($i = 0; $i < count($list, 0); $i++) {
                //查询出旅游线路车牌
                $cp = Cl::field('name,zws')->where('dd_cd_id', $list[$i]['id'])->order('zws', 'asc')->select();
                $cp = collection($cp)->toArray();
                for ($j = 0; $j < count($cp, 0); $j++) {
                    $gd[$t]['xl'] = $list[$i]['name']; //赋值线路
                    $gd[$t]['cp'] = $cp[$j]['name']; //赋值车牌信息
                    $gd[$t]['zws'] = $cp[$j]['zws']; //赋值车辆座位数

                    if (key_exists('pctime',$date)) {

                        $aa = $this->model->field('id,cd,cp,kh,kstime,jstime,mdd,jsy1,status,ddr')->where("cp='" . $cp[$j]['name'] . "'")->where("date_format(kstime,'%Y%m')=date_format('" . $date['pctime'] . "','%Y%m')")->order('kstime,cp', 'asc')->select();
                    } else {
                        $aa = $this->model->field('id,cd,cp,kh,kstime,jstime,mdd,jsy1,status,ddr')->where("cp='" . $cp[$j]['name'] . "'")->where("date_format(kstime,'%Y%m')=date_format(now(),'%Y%m')")->order('kstime,cp', 'asc')->select();
                    }
                    $aa = collection($aa)->toArray();
                    $byts1 = 0;
                    for ($k = 0; $k < count($aa, 0); $k++) {

                        if ($aa[$k]['mdd']) {
                            // $day = $ksday = $day1 = $jsday1 = $jsday = $jsday2 =$byts1= "";
                            // 获取当数字表示的月份，没有前导零date("n")
                            // $dqyf = date('n'); //取得当前月份
                            if (!isset($date['pctime'])) { //判断是否有提交月份查询
                                $dqyf = date('Ym');
                            } else {

                                $dqyf = date('Ym', strtotime($date['pctime']));
                            }


                            $ksday = date('Ym', strtotime($aa[$k]['kstime']));

                            // //对比开始月份是否小于当月，开始日期设置为1日
                            if ($ksday == $dqyf) {

                                $day = date('d', strtotime($aa[$k]['kstime'])) + 0;
                            } else {

                                $day = date('d', strtotime(date('Y-m-01', strtotime(date($aa[$k]['kstime']))))) + 0;
                            }
                            $jsday1 = date('Ym', strtotime($aa[$k]['jstime']));

                            //对比检查是否超出本月，开始日期设置为月末
                            if ($jsday1 == $dqyf) {

                                $jsday = date('d', strtotime($aa[$k]['jstime'])) + 0; //取得几号

                            } else {

                                $jsday = date('t', strtotime($aa[$k]['kstime'])) + 0; //取查询月的最后一天

                            }

                            //检查是否超出本月  获取当月天数date("t")   


                            //检查是否有套团，有就添加1行
                            if (array_key_exists('js' . $day, $gd[$t]) or array_key_exists('ks' . $day, $gd[$t])) {
                                $t += 1;
                                $gd[$t]['cp'] = $cp[$j]['name']; //赋值车牌信息
                                $gd[$t]['zws'] = $cp[$j]['zws'];
                                
                            }
                            // $gd[$t]['cp'] = $cp[$j]['name']; //赋值车牌信息
                            $gd[$t]['ks' . $day] = $day;
                            $gd[$t]['js' . $jsday] = $jsday;
                            $gd[$t]['s' . $day] = mb_substr($aa[$k]['mdd'], 0, 4)."<br>" .$aa[$k]['jsy1']. "<br>" . mb_substr($aa[$k]['kh'], 0, 4) . "<br>" . $aa[$k]['ddr'];
                            $gd[$t]['ids' . $day] = $aa[$k]['id'];
                            $gd[$t]['status' . $day] = $aa[$k]['status'];
                            $colspan = ($jsday - $day) + 1;

                            $gd[$t]['colspan' . $day] = $colspan;
                            //添加多天行程，方便检查套团
                            $byts1 += $colspan; //合计开了多少天
                            for ($w = 1; $w < $colspan; $w++) {
                                $gd[$t]['js' . ($day + $w)] = $day + $w;
                            }
                        
                        }
                    }

                    $gd[$t]['byts'] = $byts1; //一共开了多少天
                    $gd[$t]['ts'] = count($aa, 0); //统计一共有多少趟数
                    //到下一行
                  
                    $t += 1;
                }
            }
            $list = collection($gd)->toArray();

            $result = array("total" => count($gd), "rows" => $gd);

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 旅游车派车记录按月
     */
    // public function pcjl2()
    // {

    //     $this->pcjl();
    // }
    /**
     * 今日派车记录
     */
    public function jrpc()
    {
        if ($this->request->isAjax()) {
            $admin_id = $this->getDataLimitAdminIds(); //查询用户组id
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $list = $this->model
                ->field('cd,cp,kstime,jstime,jsy1,jsy2,scd,tj,mdd')
                ->where('admin_id', 'in', $admin_id)
                ->where("status = '确定'")
                ->whereTime('kstime', '<=', time())
                ->whereTime('jstime', '>=', time())
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 今日派车记录
     */
    // public function jrpc2()
    // {
    //     $this->jrpc();


    // }

    /**
     * 打印页面
     */
    public function dy()
    {
        $this->dysj();
        return $this->view->fetch();
    }

    /**
     * 打印数据
     */
    public function dysj()
    {
        $ids = $this->request->param("ids");
        // $list = $this->model->where('id', $ids)->select();
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('id', $ids)
            ->order($sort, $order)
            ->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());
        return json($result);
    }
}
